﻿using System;
using System.Collections.Generic;
using System.Linq;
using Crossroad.Core.Configs;
using Crossroad.Core.Helper;
using SqlSugar;

namespace Crossroad.Core.Data
{
    /// <summary>
    /// 数据通信模块
    /// </summary>
    public class Access<T> where T : class, new()
    {
        protected SqlSugarClient db;

        public Access()
        {
            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = AppConfig.ConnectionString,
                DbType = AppConfig.DbType,
                //从特性读取主键和自增列信息
                InitKeyType = InitKeyType.Attribute,
                //开启自动释放模式和EF原理一样我就不多解释了
                IsAutoCloseConnection = true,
                //设为true相同线程是同一个SqlConnection
                IsShardSameThread = true,
            });
            //调式代码 用来打印SQL 
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                var executeSql =
                    $"{sql}\r\n{db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}";
                LogHelper.Info(executeSql);
            };
        }

        /// <summary>
        /// 开启事物
        /// </summary>
        public void BeginTran(System.Data.IsolationLevel iso = System.Data.IsolationLevel.ReadCommitted)
        {
            db.Ado.BeginTran(iso);
        }

        /// <summary>
        /// 提交事物
        /// </summary>
        public void CommitTran()
        {
            db.Ado.CommitTran();
        }

        /// <summary>
        /// 回滚事物
        /// </summary>
        public void RollbackTran()
        {
            db.Ado.RollbackTran();
        }


    }
}
